import random

# Create your views here.
from django.conf import settings
from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from bookSystem.utils.exceptions import logger
from celery_tasks.sms import tasks as sms_tasks
from bookSystem.utils.captcha.captcha import captcha
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class SMSCodeView(APIView):
    """发送短信验证码"""
    def get(self, request, mobile):

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_codes')

        # 60秒内不允许重发发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({"message": "发送短信过于频繁"}, status=status.HTTP_400_BAD_REQUEST)

        # 生成和发送短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        print("短信验证码:{}".format(sms_code))
        logger.debug(sms_code)

        # 发送短信验证码
        sms_tasks.send_sms_code.delay(mobile, sms_code, '5')

        # 以下代码演示redis管道pipeline的使用
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, 300, sms_code)  # 信息保存时间
        pl.setex('send_flag_%s' % mobile, 60, 1)    # 连续发送的时间锁
        # 执行
        pl.execute()

        # 响应发送短信验证码结果
        return Response({"message": "OK"})


    @staticmethod
    def checkSMSCode(mobile):
        """
        验证短信验证码
        :param mobile:
        :param sms_code:
        :return:
        """
        # 建立redis链接
        conn = get_redis_connection("verify_codes")
        try:
            real_sms = conn.get("sms_%s" % mobile).decode()
        except:
            return None
        return real_sms


class FindPSDSMSCodeView(APIView):
    """找回密码二:发送短信"""
    def get(self, reuest):
        access_token = reuest.query_params['access_token']
        tjs = TJS(settings.SECRET_KEY, 300)
        token_data = tjs.loads(access_token)
        mobile = token_data['mobile']
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_codes')

        # 60秒内不允许重发发送短信
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({"message": "发送短信过于频繁"}, status=status.HTTP_400_BAD_REQUEST)

        # 生成和发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print("短信验证码:{}".format(sms_code))
        logger.debug(sms_code)

        # 发送短信验证码
        sms_tasks.send_sms_code.delay(mobile, sms_code, '5')
        # redis管道pipeline的使用
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, 300, sms_code)  # 信息保存时间
        pl.setex('send_flag_%s' % mobile, 60, 1)  # 连续发送的时间锁
        # 执行
        pl.execute()

        # 响应发送短信验证码结果
        return Response({"message": "OK"})


class ImageCheckViews(APIView):
    """图片验证码"""

    def get(self, request, imgid):
        """
        生成团验证码
        image_codes/7aa25ae7-b93b-48df-ba20-669e276352ae/
        :return:
        """
        img_name, text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % imgid, 300, text)
        print("图片验证码:%s" % text)

        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="text/html")

    @staticmethod
    def check_imagecode(imgid):
        """
        获取真实的图片验证码
        :param imgid:
        :return:
        """
        # 建立redis链接
        conn = get_redis_connection("verify_codes")
        real_imgcode = conn.get("img_%s" % imgid).decode()
        return real_imgcode.lower()